﻿using System;
using System.Web;
using System.Web.SessionState;
using System.Collections;
using System.IO;
using System.Text.RegularExpressions;
using LitJson;
using System.Collections.Generic;

namespace msBsc.WebUi
{
    public class PageAjaxHandler : IHttpHandler,IRequiresSessionState
    {
        public PageAjaxHandler()
        {
        }

        private string GetFormParam(string ParamName)
        {
            if (string.IsNullOrEmpty(HttpContext.Current.Request.Params[ParamName]))
                return string.Empty;
            else
                return HttpContext.Current.Request.Params[ParamName];
        }

        public void ProcessRequest(HttpContext context)
        {
            doPageAjax(context);
        }

        private void SetLoginByCooke(HttpContext context)
        {
            string token = context.Request.QueryString["COOKATHID"];

            if (token != null && token.Length > 10)
            {
                token = msBsc.AppLogic.Cfg.DesCry.uncMe(token, "cookesc");
                System.Web.Security.FormsAuthenticationTicket ticket = System.Web.Security.FormsAuthentication.Decrypt(token);

                if (ticket != null)
                {
                    System.Web.Security.FormsIdentity identity = new System.Web.Security.FormsIdentity(ticket);
                    string[] roles = { "*" }; //System.Web.Security.Roles.GetRolesForUser(identity.Name); 注意这里，如果你没有启用asp.net权限系统，会报错。
                    System.Security.Principal.GenericPrincipal principal = new System.Security.Principal.GenericPrincipal(identity, roles);
                    context.User = principal;
                }
            }
        }

                //msBsc.AppLogic.Cfg.UserInfo oUserInfo = new AppLogic.Cfg.UserInfo();
        private void doPageAjax(HttpContext context)
        {
            try
            {
                context.Response.Cache.SetNoStore();

                //UserInfo oUserInfo = new UserInfo();

                ////远程文件上传登录判断
                //string sSVC_F_SAVE = GetFormParam("SVC_F_SAVE");
                //string sUSER_CRY = GetFormParam("USER_CRY");
                //if (!string.IsNullOrEmpty(sSVC_F_SAVE) && sSVC_F_SAVE == "1" && !string.IsNullOrEmpty(sUSER_CRY))
                //{
                //    msBsc.SvRef.UserInfo.Login(sUSER_CRY);
                //}



                //if (!msBsc.SvRef.UserInfo.Online)
                //{
                    //msBsc.WebUi.BPlogin owtem = new msBsc.WebUi.BPlogin();
                    //owtem.SetLogin(this, false);
                //}
                if (!string.IsNullOrEmpty(context.Request.Params["LOGINOUT"]))
                {
                    if (context.Request.Params["LOGINOUT"] == "1")
                    {
                        msBsc.SvRef.UserInfo.ExitSys();
                        msBsc.SvRef.UserInfo.OperDealerId = null;
                    }
                }
                else if (!string.IsNullOrEmpty(context.Request.Params["GETLOGIN"]))
                {
                    context.Response.ClearContent();
                    if (context.Request.Params["GETLOGIN"] == "1")
                    {
                        msBsc.WebUi.Code.QtHtmlGet oQtHtmlGet = new Code.QtHtmlGet();

                        context.Response.Write(oQtHtmlGet.GetHeaderLoginInfo());
                    }
                    return;
                }
                else if (!string.IsNullOrEmpty(context.Request.Params["GETLOGIN_ST"]))
                {
                    if (context.Request.Params["GETLOGIN_ST"] == "1")
                    {
                        context.Response.ClearContent();
                        context.Response.Write(msBsc.SvRef.UserInfo.Online ? msBsc.SvRef.UserInfo.Operator + "," + msBsc.SvRef.UserInfo.OperType : "0");
                        return;
                    }
                }
                else if (!string.IsNullOrEmpty(context.Request.Params["GET_LIKE_JSON"]))
                {
                    context.Response.ClearContent();
                    if (context.Request.Params["GET_LIKE_JSON"] == "1" )
                    {
                        using (msBsc.AppLogic.DataAlc.CBizShpGoodsInfo ocart = new AppLogic.DataAlc.CBizShpGoodsInfo())
                        {
                            context.Response.Write(ocart.GetGuessLikeGoodsJson(context.Request.Params["G_IDS"]));
                        }
                    }
                    return;
                }
                else if (!string.IsNullOrEmpty(context.Request.Params["GET_PAGE_JSON"]))
                {
                    context.Response.ClearContent();
                    if (context.Request.Params["GET_PAGE_JSON"] == "1")
                    {
                        msBsc.WebUi.Code.PageHtmlGet ocart = new msBsc.WebUi.Code.PageHtmlGet();
                        context.Response.Write(ocart.GetPageJson(context.Request.Params["NO"]));
                    }
                    return;
                }
                else if (!string.IsNullOrEmpty(context.Request.Params["ADD_SHOP_COLL"]))
                {
                    context.Response.ClearContent();
                    if (context.Request.Params["ADD_SHOP_COLL"] == "1" && msBsc.SvRef.UserInfo.Online)
                    {
                        using (msBsc.AppLogic.DataAlc.CBizShpCustomerShopCollect ocart = new AppLogic.DataAlc.CBizShpCustomerShopCollect())
                        {
                            ocart.AddCollect(msBsc.SvRef.UserInfo.Operator, context.Request.QueryString.Get("ID"));
                            context.Response.Write("1");
                        }
                    }
                    return;
                }
                else if (!string.IsNullOrEmpty(context.Request.Params["DEL_SHOP_COLL"]))
                {
                    context.Response.ClearContent();
                    if (context.Request.Params["ADD_SHOP_COLL"] == "1" && msBsc.SvRef.UserInfo.Online)
                    {
                        using (msBsc.AppLogic.DataAlc.CBizShpCustomerShopCollect ocart = new AppLogic.DataAlc.CBizShpCustomerShopCollect())
                        {
                            ocart.DelCollect(msBsc.SvRef.UserInfo.Operator, context.Request.QueryString.Get("ID"));
                            context.Response.Write("1");
                        }
                    }
                    return;
                }
                else if (!string.IsNullOrEmpty(context.Request.Params["GET_TAGSUGGEST_JSON"]))
                {
                    context.Response.ClearContent();
                    if (context.Request.Params["GET_TAGSUGGEST_JSON"] == "1")
                    {
                        using (msBsc.AppLogic.DataAlc.CBizShpGoodsInfo ocart = new AppLogic.DataAlc.CBizShpGoodsInfo())
                        {
                            context.Response.Write(ocart.GetTagSuggestJson(context.Request.Params["G_IDS"]));
                        }
                    }
                    return;
                }
                else if (!string.IsNullOrEmpty(context.Request.Params["GETCART_DATA"]))
                {
                    context.Response.ClearContent();
                    if (context.Request.Params["GETCART_DATA"] == "1" && msBsc.SvRef.UserInfo.Online)
                    {
                        using (msBsc.AppLogic.DataAlc.CBizShpCustomerCart ocart = new AppLogic.DataAlc.CBizShpCustomerCart())
                        {

                            context.Response.Write(ocart.GetUserCartJson(msBsc.SvRef.UserInfo.Operator));
                        }
                    }
                    return;
                }
                else if (!string.IsNullOrEmpty(context.Request.Params["ADDCART_DATA"]))
                {
                    context.Response.ClearContent();
                    if (context.Request.Params["ADDCART_DATA"] == "1" && msBsc.SvRef.UserInfo.Online)
                    {
                        using (msBsc.AppLogic.DataAlc.CBizShpCustomerCart ocart = new AppLogic.DataAlc.CBizShpCustomerCart())
                        {
                            int iOrderQty = ocart.AddUserCart(context.Request.QueryString.Get("g"), context.Request.QueryString.Get("b"), context.Request.QueryString.Get("p1"), context.Request.QueryString.Get("p2"), context.Request.QueryString.Get("q"));
                            if (!string.IsNullOrEmpty(context.Request.Params["REF_LIST"]) && context.Request.Params["REF_LIST"] == "1")
                            {
                                context.Response.Write(ocart.GetUserCartJson(msBsc.SvRef.UserInfo.Operator));
                            }
                            else
                            {
                                System.Data.DataSet dstm = ocart.SelectCartStatistic(msBsc.SvRef.UserInfo.Operator);
                                if (dstm.Tables[0].Rows.Count > 0)
                                {
                                    context.Response.Write(iOrderQty.ToString() + "," + dstm.Tables[0].Rows[0]["ALL_GOODS"].ToString());
                                }
                            }
                        }
                    }
                    return;
                }
                else if (!string.IsNullOrEmpty(context.Request.Params["DELCART_DATA"]))
                {
                    context.Response.ClearContent();
                    if (context.Request.Params["DELCART_DATA"] == "1" && msBsc.SvRef.UserInfo.Online)
                    {
                        using (msBsc.AppLogic.DataAlc.CBizShpCustomerCart ocart = new AppLogic.DataAlc.CBizShpCustomerCart())
                        {
                            int iOrderQty=ocart.AddUserCart(context.Request.QueryString.Get("g"), context.Request.QueryString.Get("b"), context.Request.QueryString.Get("p1"), context.Request.QueryString.Get("p2"), context.Request.QueryString.Get("q"));
                            if (!string.IsNullOrEmpty(context.Request.Params["REF_LIST"]) && context.Request.Params["REF_LIST"] == "1")
                            {
                                context.Response.Write(ocart.GetUserCartJson(msBsc.SvRef.UserInfo.Operator));
                            }
                            else
                            {
                                System.Data.DataSet dstm = ocart.SelectCartStatistic(msBsc.SvRef.UserInfo.Operator);
                                if (dstm.Tables[0].Rows.Count > 0)
                                {
                                    context.Response.Write(iOrderQty.ToString() + "," + dstm.Tables[0].Rows[0]["ALL_GOODS"].ToString());
                                }
                            }
                        }
                    }
                    return;
                }
                else if (!string.IsNullOrEmpty(context.Request.Params["VDC"]))
                {
                    if (context.Request.Params["VDC"] == "1" && !string.IsNullOrEmpty(context.Request.Params["PRAD"]))
                    {
                        msBsc.Cls.ValidateCode oValidateCode = new msBsc.Cls.ValidateCode();
                        context.Session[context.Request.Params["PRAD"].ToString() + msBsc.Cls.ValidateCode.VALIDATECODEKEY] = oValidateCode.CreateCode(4);

                        context.Response.ClearContent();
                        context.Response.ContentType = "image/Gif";
                        context.Response.BinaryWrite(oValidateCode.CreateValidateImage());
                        return;
                    }
                    else if (context.Request.Params["VDC"] == "2" && !string.IsNullOrEmpty(context.Request.Params["INPVDCD"]) && !string.IsNullOrEmpty(context.Request.Params["PRAD"]))
                    {
                        context.Response.ClearContent();
                        if (context.Session[context.Request.Params["PRAD"].ToString() + msBsc.Cls.ValidateCode.VALIDATECODEKEY].ToString() == context.Request.Params["INPVDCD"].ToString())
                        {
                            context.Response.Write('1');
                        }
                        else
                        {
                            context.Response.Write('0');
                        }
                        return;
                    }
                }
                else
                {
                    if (!msBsc.SvRef.UserInfo.Online)
                    {
                        SetLoginByCooke(context);
                    }
                    if (msBsc.SvRef.UserInfo.Online)
                    {
                        if (!string.IsNullOrEmpty(context.Request.Params["F_UPLOAD"]))
                        {
                            UPfile(context);
                            context.Response.End();
                            return;
                        }
                        if (!string.IsNullOrEmpty(context.Request.Params["F_MANA"]))
                        {
                            ManaFile(context);
                            context.Response.End();
                            return;
                        }
                    }
                } 


                context.Response.Write("OK");
            }
            catch (Exception err)
            {
                context.Response.Write("错误-服务器端：" + err.Message + "\r\n错误堆栈：" + err.Source);
            }
        }
         

        private void ManaFile(HttpContext context)
        {
            //String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1);

            ////根目录路径，相对路径
            //String rootPath = "../attached/";
            ////根目录URL，可以指定绝对路径，比如 http://www.yoursite.com/attached/
            //String rootUrl = aspxUrl + "../attached/";
            //图片扩展名
            String fileTypes = "gif,jpg,jpeg,png,bmp";

            String currentPath = "";
            String currentUrl = "";
            String currentDirPath = "";
            String moveupDirPath = "";


            string strParentId = context.Request.Params.Get("ParentId");
            string strType1 = context.Request.Params.Get("rType1");
            string strType2 = context.Request.Params.Get("rType2");
            string strRelId = context.Request.Params.Get("RelId");



            //String dirPath = context.Server.MapPath(rootPath);
            //String dirName = context.Request.QueryString["dir"];
            //if (!String.IsNullOrEmpty(dirName))
            //{
            //    if (Array.IndexOf("image,flash,media,file".Split(','), dirName) == -1)
            //    {
            //        context.Response.Write("Invalid Directory name.");
            //        context.Response.End();
            //    }
            //    dirPath += dirName + "/";
            //    rootUrl += dirName + "/";
            //    if (!Directory.Exists(dirPath))
            //    {
            //        Directory.CreateDirectory(dirPath);
            //    }
            //}

            //根据path参数，设置各路径和URL
            String path = context.Request.QueryString["path"];
            path = String.IsNullOrEmpty(path) ? "" : path;
            //if (path == "")
            //{
            //    currentPath = dirPath;
            //    currentUrl = rootUrl;
            //    currentDirPath = "";
            //    moveupDirPath = "";
            //}
            //else
            //{
            //    currentPath = dirPath + path;
            //    currentUrl = rootUrl + path;
            //    currentDirPath = path;
            //    moveupDirPath = Regex.Replace(currentDirPath, @"(.*?)[^\/]+\/$", "$1");
            //}

            ////排序形式，name or size or type
            //String order = context.Request.QueryString["order"];
            //order = String.IsNullOrEmpty(order) ? "" : order.ToLower();

            ////不允许使用..移动到上一级目录
            //if (Regex.IsMatch(path, @"\.\."))
            //{
            //    context.Response.Write("Access is not allowed.");
            //    context.Response.End();
            //}
            ////最后一个字符不是/
            //if (path != "" && !path.EndsWith("/"))
            //{
            //    context.Response.Write("Parameter is not valid.");
            //    context.Response.End();
            //}
            ////目录不存在或不是目录
            //if (!Directory.Exists(currentPath))
            //{
            //    context.Response.Write("Directory does not exist.");
            //    context.Response.End();
            //}

            ////遍历目录取得文件信息
            //string[] dirList = Directory.GetDirectories(currentPath);
            //string[] fileList = Directory.GetFiles(currentPath);

            //switch (order)
            //{
            //    case "size":
            //        Array.Sort(dirList, new NameSorter());
            //        Array.Sort(fileList, new SizeSorter());
            //        break;
            //    case "type":
            //        Array.Sort(dirList, new NameSorter());
            //        Array.Sort(fileList, new TypeSorter());
            //        break;
            //    case "name":
            //    default:
            //        Array.Sort(dirList, new NameSorter());
            //        Array.Sort(fileList, new NameSorter());
            //        break;
            //}

            //for (int i = 0; i < dirList.Length; i++)
            //{
            //    DirectoryInfo dir = new DirectoryInfo(dirList[i]);
            //    Hashtable hash = new Hashtable();
            //    hash["is_dir"] = true;
            //    hash["has_file"] = (dir.GetFileSystemInfos().Length > 0);
            //    hash["filesize"] = 0;
            //    hash["is_photo"] = false;
            //    hash["filetype"] = "";
            //    hash["filename"] = dir.Name;
            //    hash["datetime"] = dir.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
            //    dirFileList.Add(hash);
            //}
            //for (int i = 0; i < fileList.Length; i++)
            //{
            //    FileInfo file = new FileInfo(fileList[i]);
            //    Hashtable hash = new Hashtable();
            //    hash["is_dir"] = false;
            //    hash["has_file"] = false;
            //    hash["filesize"] = file.Length;
            //    hash["is_photo"] = (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) >= 0);
            //    hash["filetype"] = file.Extension.Substring(1);
            //    hash["filename"] = file.Name;
            //    hash["datetime"] = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
            //    dirFileList.Add(hash);
            //}






            Hashtable result = new Hashtable();
            result["moveup_dir_path"] = moveupDirPath;
            result["current_dir_path"] = currentDirPath;
            result["current_url"] = currentUrl;
            List<Hashtable> dirFileList = new List<Hashtable>();
            result["file_list"] = dirFileList;



            using (msBsc.AppLogic.DataAlc.CBizSysFile ooo = new msBsc.AppLogic.DataAlc.CBizSysFile())
            {
                    if (string.IsNullOrEmpty(strParentId))
                    {
                        strParentId = path;
                    }
                    System.Data.DataSet dsDir = null;
                    if (strType1 == "0")
                    {
                        dsDir = ooo.SelectForSysImgMana(strParentId);
                    }
                    else
                    {
                        dsDir = ooo.SelectForCustomerImgMana(strParentId, msBsc.SvRef.UserInfo.Operator);
                    }

                    if (!string.IsNullOrEmpty(strParentId))
                    { 
                        System.Data.DataSet dsP = ooo.DataObj.QueryBySQL("SELECT PARENT_FILE_ID FROM SYS_FILE WHERE FILE_ID='" + strParentId + "'");
                        if (dsP.Tables[0].Rows.Count > 0)
                        { 
                            Hashtable hash = new Hashtable();
                            hash["is_dir"] = true;
                            hash["has_file"] = true;
                            hash["filesize"] = 0;
                            hash["is_photo"] = false;
                            hash["filetype"] = "";
                            hash["filename"] = "返回上级";
                            hash["fileurl"] = dsP.Tables[0].Rows[0]["PARENT_FILE_ID"].ToString();
                            hash["datetime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            dirFileList.Add(hash);
                        }
                    }


                    for (int i = dsDir.Tables[0].Rows.Count - 1; i >= 0; i--)
                    {
                        if (dsDir.Tables[0].Rows[i]["IS_DIR"].ToString() == "True")
                        {
                            Hashtable hash = new Hashtable();
                            hash["is_dir"] = dsDir.Tables[0].Rows[i]["IS_DIR"].ToString() == "True";
                            hash["has_file"] = true;
                            hash["filesize"] = 0;
                            hash["is_photo"] = false;
                            hash["filetype"] = "";
                            hash["filename"] = dsDir.Tables[0].Rows[i]["FILE_NME"].ToString();
                            hash["fileurl"] = dsDir.Tables[0].Rows[i]["FILE_ID"].ToString();
                            hash["datetime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            dirFileList.Add(hash);
                        }
                        else
                        {
                            FileInfo file = new FileInfo(context.Server.MapPath(dsDir.Tables[0].Rows[i]["FILE_V_PATH"].ToString()));
                            if (file.Exists)
                            {
                                Hashtable hash = new Hashtable();
                                hash["is_dir"] = false;
                                hash["has_file"] = false;
                                hash["filesize"] = file.Length;
                                hash["is_photo"] = (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) >= 0);
                                hash["filetype"] = file.Extension.Substring(1);
                                hash["filename"] = dsDir.Tables[0].Rows[i]["FILE_NME"].ToString() + "." + dsDir.Tables[0].Rows[i]["FILE_EXT"].ToString();
                                hash["fileurl"] = dsDir.Tables[0].Rows[i]["FILE_V_PATH"].ToString();
                                hash["datetime"] = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                                dirFileList.Add(hash);
                            } 
                        }
                    }
                //}
                //else
                //{
                //    string strSql = "SELECT IMG_CLASSIFY_ID,CLASSIFY_NME FROM SHP_GOODS_IMG_CLASSIFY WHERE (USER_NME='" + msBsc.SvRef.ApplicationConst.Const.Operator + "' OR USER_NME='') order by CLASSIFY_NME asc";

                //    System.Data.DataSet dsDir = ooo.DataObj.QueryBySQL(strSql);

                //    for (int i = dsDir.Tables[0].Rows.Count - 1; i >= 0; i--)
                //    {
                //        Hashtable hash = new Hashtable();
                //        hash["is_dir"] = true;
                //        hash["has_file"] = true;
                //        hash["filesize"] = 0;
                //        hash["is_photo"] = false;
                //        hash["filetype"] = "";
                //        hash["filename"] = dsDir.Tables[0].Rows[i]["CLASSIFY_NME"].ToString();
                //        hash["fileurl"] = dsDir.Tables[0].Rows[i]["IMG_CLASSIFY_ID"].ToString();
                //        hash["datetime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //        dirFileList.Add(hash);
                //    }
                //    {
                //        Hashtable hash = new Hashtable();
                //        hash["is_dir"] = true;
                //        hash["has_file"] = true;
                //        hash["filesize"] = 0;
                //        hash["is_photo"] = false;
                //        hash["filetype"] = "";
                //        hash["filename"] = "全部分类";
                //        hash["fileurl"] = "all";
                //        hash["datetime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //        dirFileList.Add(hash);
                //    }

                //    if (path == "all")
                //    {
                //        strSql = "SELECT FILE_V_PATH,FILE_NME FROM SYS_FILE WHERE USER_NME='" + msBsc.SvRef.ApplicationConst.Const.Operator + "' AND RELATION_TYPE_CID1='1' ORDER BY FILE_NME ASC";
                //    }
                //    else if (path == "")
                //    {
                //        strSql = "SELECT FILE_V_PATH,FILE_NME FROM SYS_FILE WHERE USER_NME='" + msBsc.SvRef.ApplicationConst.Const.Operator + "' AND RELATION_TYPE_CID1='1' AND (RELATION_TYPE_CID2='' OR RELATION_TYPE_CID2 IS NULL) ORDER BY FILE_NME ASC";
                //    }
                //    else
                //    {
                //        strSql = "SELECT FILE_V_PATH,FILE_NME FROM SYS_FILE WHERE USER_NME='" + msBsc.SvRef.ApplicationConst.Const.Operator + "' AND RELATION_TYPE_CID1='1' AND RELATION_TYPE_CID2='" + path + "' ORDER BY FILE_NME ASC";
                //    }
                //    System.Data.DataSet dslist = ooo.DataObj.QueryBySQL(strSql);



                //    //System.Data.DataSet dslist = ooo.SelectByImgClass("");
                //    result["total_count"] = dsDir.Tables[0].Rows.Count + dslist.Tables[0].Rows.Count;
                //    for (int i = dslist.Tables[0].Rows.Count - 1; i >= 0; i--)
                //    {
                //        //if (dslist.Tables[0].Rows[i]["RELATION_TYPE_CID2"].ToString() == string.Empty)
                //        //{
                //        //    DirectoryInfo dir = new DirectoryInfo(dirList[i]);
                //        //    Hashtable hash = new Hashtable();
                //        //    hash["is_dir"] = true;
                //        //    hash["has_file"] = true;
                //        //    hash["filesize"] = 0;
                //        //    hash["is_photo"] = false;
                //        //    hash["filetype"] = "";
                //        //    hash["filename"] = dslist.Tables[0].Rows[i]["CLASSIFY_NME"].ToString();
                //        //    hash["datetime"] = ((DateTime)dslist.Tables[0].Rows[i]["REC_UPDATE_DT"]).ToString("yyyy-MM-dd HH:mm:ss");
                //        //    dirFileList.Add(hash);
                //        //}

                //        FileInfo file = new FileInfo(context.Server.MapPath(dslist.Tables[0].Rows[i]["FILE_V_PATH"].ToString()));
                //        if (file.Exists)
                //        {
                //            Hashtable hash = new Hashtable();
                //            hash["is_dir"] = false;
                //            hash["has_file"] = false;
                //            hash["filesize"] = file.Length;
                //            hash["is_photo"] = (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) >= 0);
                //            hash["filetype"] = file.Extension.Substring(1);
                //            hash["filename"] = dslist.Tables[0].Rows[i]["FILE_NME"].ToString();
                //            hash["fileurl"] = dslist.Tables[0].Rows[i]["FILE_V_PATH"].ToString();
                //            hash["datetime"] = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                //            dirFileList.Add(hash);
                //        }
                //    }
                //}
            }




            context.Response.AddHeader("Content-Type", "application/json; charset=UTF-8");
            context.Response.Write(JsonMapper.ToJson(result));
            context.Response.End();
        }
         
        private void UPfile(HttpContext context)
        {




            context.Response.Clear();
            //context.Response.ContentType = "text/plain";
            //context.Response.Charset = "UTF-8";

            //context.Response.AddHeader("Content-Type", "text/html; charset=GBK");

            //context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");


            string strParentId = context.Request.Params.Get("ParentId");
            bool blIsDir = context.Request.Params.Get("IsDir") == "1";
            string strDirNme = context.Request.Params.Get("DirNme");
            string strFileId = context.Request.Params.Get("FileId");
            string strRelId = context.Request.Params.Get("RelId");
            string strType1 = context.Request.Params.Get("rType1");
            string strType2 = context.Request.Params.Get("rType2");
            bool blSave = context.Request.Params.Get("blSave") == "1";
            if (string.IsNullOrEmpty(strType1))
            {
                strType1 = "1";
            }

            if (blIsDir)
            {
                if (string.IsNullOrEmpty(strDirNme))
                {
                    strDirNme = "新建文件夹";
                }
                using (msBsc.AppLogic.DataAlc.CBizSysFile ooo = new msBsc.AppLogic.DataAlc.CBizSysFile())
                {
                    //0EA51FE9ZZ1X1 未分类
                    context.Response.Write(ooo.SaveImgToServer(null, strFileId, strRelId, strType1, strType2, "", strParentId, blIsDir, strDirNme));//"0EA51FE9ZZ1X1"
                }
                return;
            }




            //定义允许上传的文件扩展名
            Hashtable extTable = new Hashtable();
            extTable.Add("image", "gif,jpg,jpeg,png,bmp");
            extTable.Add("flash", "swf,flv");
            extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
            extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

            //context.Response.Write("{\"error\":1,\"url\":\"\",\"fid\":\"\",\"message\":\"请选择文件," + msBsc.SvRef.CString.StrEncodingConvert("请选择文件。", System.Text.Encoding.Default, System.Text.Encoding.UTF8) + "\"}");
            //return;
            //最大文件大小
            int maxSize = 1024000;

            bool blfnmeutf8 = false;
            HttpPostedFile imgFile = context.Request.Files["file"];
            if (imgFile == null)
            {
                imgFile = context.Request.Files["imgFile"];
            }
            if (imgFile == null)
            {
                imgFile = context.Request.Files["imgFileSWF"];
                blfnmeutf8 = true;
            }
            if (imgFile == null)
            {
                context.Response.Write("{\"error\":1,\"url\":\"\",\"fid\":\"\",\"message\":\"请选择文件。\"}");
                return;
            }
            String fileName = imgFile.FileName;


            //if (blfnmeutf8)
            //{
            //    string fname = fileName;//得到客户端的文件名,这里是乱码

            //    try
            //    {

            //        byte[] bytes = System.Text.Encoding.Convert(

            //               System.Text.Encoding.UTF8,//swfupload默认是用utf-8上传的，如果是其它编码，则改成其它编码

            //               System.Text.Encoding.Default,

            //               System.Text.Encoding.Default.GetBytes(fname));//关键是这句，强制转换编码

            //        using (Stream stream = new MemoryStream(bytes))
            //        {

            //            using (StreamReader objReader = new StreamReader(stream, System.Text.Encoding.Default))
            //            {
            //                fname = objReader.ReadToEnd();//正确的文件名

            //                objReader.Close();

            //                objReader.Dispose();
            //            }
            //        }
            //        fileName = fname;
            //    }

            //    catch (Exception) { }

            //}





            String fileExt = Path.GetExtension(fileName).ToLower();

            if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
            {
                context.Response.Write("{\"error\":1,\"url\":\"\",\"fid\":\"\",\"message\":\"上传文件大小超过限制。\"}");
                return; 
            }

            string strFType = context.Request.QueryString["fType"];
            if (String.IsNullOrEmpty(strFType))
            {
                strFType = "image";
            }
            if (strFType != "mana")
            {
                if (!extTable.ContainsKey(strFType))
                {
                    context.Response.Write("{\"error\":1,\"url\":\"\",\"fid\":\"\",\"message\":\"文件类型错误。\"}");
                    return;
                }
                if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[strFType]).Split(','), fileExt.Trim().Replace(".","").ToLower()) == -1)
                {
                    context.Response.Write("{\"error\":1,\"url\":\"\",\"fid\":\"\",\"message\":\"" + "上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[strFType]) + "格式。" + "\"}");
                    return;
                }
            }







            //string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"]) + "\\";

            if (imgFile != null)
            {
                if (blSave)
                {
                    using (msBsc.AppLogic.DataAlc.CBizSysFile ooo = new msBsc.AppLogic.DataAlc.CBizSysFile())
                    {
                        //0EA51FE9ZZ1X1 未分类
                        context.Response.Write(ooo.SaveImgToServer(imgFile, strFileId, strRelId, strType1, strType2, "", strParentId, blIsDir, strDirNme, blfnmeutf8));//"0EA51FE9ZZ1X1"
                    }
                }
                else
                {
                    using (msBsc.AppLogic.DataAlc.CBizSysFile ooo = new msBsc.AppLogic.DataAlc.CBizSysFile())
                    {
                        string filename = msBsc.SvRef.ApplicationConst.Const.GenerateStrId() + fileExt;
                        string strVpath = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.UrlBase + msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strTemXmlFileVDir + filename;
                        //imgFile.SaveAs(HttpContext.Current.Server.MapPath(strVpath));
                        ooo.SaveAsPostFile(imgFile, HttpContext.Current.Server.MapPath(strVpath));
                        context.Response.Write("{\"error\":0,\"url\":\"" + msBsc.AppLogic.Cfg.HttpTools.stringToJson(strVpath) + "\",\"fid\":\"" + "" + "\",\"message\":\"\"}");
                    }
                }
            } 




            ////HttpContext context = HttpContext.Current;
            ////context.Response.ContentType = "text/plain";  //响应数据类型
            //if (context.Request.Files.Count > 0 && context.Request.Files[0].ContentLength != 0)
            //{
            //    //decimal id;
            //    HttpPostedFile file = context.Request.Files[0];   //得到上传文件的对象
            //    System.Random rd = new Random();
            //    string strFileNme = "";
            //    string savefile = "";
            //    string saveVfile = "";
            //    if (GetFormParam("PAGE") == "wfSysUserEmailHandle"
            //        || GetFormParam("PAGE") == "wfFwsCsEobSplitCntrEmailSend")
            //    {
            //        strFileNme = System.DateTime.Now.ToString("yyyyMddHHmmss") + "-" + file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1);
            //        //savefile = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strEmployFileDir + strFileNme;
            //        //saveVfile = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strEmployFileVDir + strFileNme;
            //    }
            //    else
            //    {
            //        strFileNme = System.DateTime.Now.ToString("yyMddHHmmss") + rd.Next(1111, 9999).ToString() + System.IO.Path.GetExtension(file.FileName);

            //        savefile = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strTemXmlFileDir + strFileNme;
            //        saveVfile = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strTemXmlFileVDir + strFileNme;
            //    }

            //    //string ext = "";
            //    //switch (Path.GetExtension(file.FileName))
            //    //{
            //    //    case ".xlsx":
            //    //        ext = ".xls";
            //    //        break;
            //    //    case ".docx":
            //    //        ext = ".doc";
            //    //        break;
            //    //    case ".pptx":
            //    //        ext = ".ppt";
            //    //        break;
            //    //    default:
            //    //        ext = Path.GetExtension(file.FileName);
            //    //        break;
            //    //}
            //    //string DownPath = DateTime.Now.ToFileTime().ToString() + ext;
            //    //string savefile = Path.Combine(path, DownPath);
            //    ////文件信息写入数据库
            //    //using (var db = dbLinq.GetErpData())
            //    //{
            //    //    _AY_AjaxUpFile f = new _AY_AjaxUpFile();
            //    //    f.DownPath = DownPath;
            //    //    f.FileName = Path.GetFileName(file.FileName);
            //    //    f.FileType = Path.GetExtension(file.FileName);
            //    //    f.FileLenth = file.ContentLength.ToString();
            //    //    f.UpMan = "";
            //    //    f.UpTime = System.DateTime.Now;
            //    //    db._AY_AjaxUpFile.InsertOnSubmit(f);
            //    //    try
            //    //    {
            //    //        db.SubmitChanges();
            //    //        id = f.ID;  // you can access your newRecord to get the ID
            //    //    }
            //    //    catch (Exception)
            //    //    {
            //    //        throw;
            //    //    }
            //    //}


            //    file.SaveAs(savefile);  //最核心的地方，实现文件上传

            //    //string sSVC_F_SAVE = GetFormParam("SVC_F_SAVE");
            //    //string sUSER_CRY = GetFormParam("USER_CRY");
            //    //string strfileid = "";
            //    //if (!string.IsNullOrEmpty(sSVC_F_SAVE) && sSVC_F_SAVE == "1" && !string.IsNullOrEmpty(sUSER_CRY))
            //    //{
            //    //    string strRelId = GetFormParam("REL_ID");
            //    //    string strRelType1 = GetFormParam("REL_TYPE1");
            //    //    string strRelType2 = GetFormParam("REL_TYPE2");
            //    //    string strFileNo = GetFormParam("FILE_NO");
            //    //    string strFileNmeSave = GetFormParam("FILE_NME");
            //    //    string strRemarks = GetFormParam("REMARKS");
            //    //    using (msBsc.AppLogic.Bse.CBizSysFile ofile = new AppLogic.Bse.CBizSysFile())
            //    //    {
            //    //        strfileid = ofile.UploadFile(new System.IO.FileInfo(savefile), strRelId, strRelType1, strRelType2, strFileNo, strFileNmeSave, strRemarks, true);
            //    //    }
            //    //}

                 
            //    context.Response.Clear();
            //    context.Response.Write("[{");
            //    context.Response.Write(string.Format("\"spath\":\"{0}\",\"vpath\":\"{1}\",\"fileid\":\"{2}\"", msBsc.AppLogic.Cfg.HttpTools.stringToJson(strFileNme), msBsc.AppLogic.Cfg.HttpTools.stringToJson(saveVfile), ""));
            //    context.Response.Write("}]");

            //}
        }


        public bool IsReusable
        {
            get { return true; }
        }



        public class NameSorter : IComparer
        {
            public int Compare(object x, object y)
            {
                if (x == null && y == null)
                {
                    return 0;
                }
                if (x == null)
                {
                    return -1;
                }
                if (y == null)
                {
                    return 1;
                }
                FileInfo xInfo = new FileInfo(x.ToString());
                FileInfo yInfo = new FileInfo(y.ToString());

                return xInfo.FullName.CompareTo(yInfo.FullName);
            }
        }

        public class SizeSorter : IComparer
        {
            public int Compare(object x, object y)
            {
                if (x == null && y == null)
                {
                    return 0;
                }
                if (x == null)
                {
                    return -1;
                }
                if (y == null)
                {
                    return 1;
                }
                FileInfo xInfo = new FileInfo(x.ToString());
                FileInfo yInfo = new FileInfo(y.ToString());

                return xInfo.Length.CompareTo(yInfo.Length);
            }
        }

        public class TypeSorter : IComparer
        {
            public int Compare(object x, object y)
            {
                if (x == null && y == null)
                {
                    return 0;
                }
                if (x == null)
                {
                    return -1;
                }
                if (y == null)
                {
                    return 1;
                }
                FileInfo xInfo = new FileInfo(x.ToString());
                FileInfo yInfo = new FileInfo(y.ToString());

                return xInfo.Extension.CompareTo(yInfo.Extension);
            }
        }
    }
}